﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace Emoticon_Tools
{
    /// <summary>
    /// CommonContextData
    /// </summary>
    public class CommonContextData
    {
        /// <summary>
        ///
        /// </summary>
        public static string[] character = { "æ", "ʌ", "ə", "ɔ", "ʃ", "ʒ", "ð", "ŋ", "ɜ", "ʊ", "\\u", "\\f" };

        /// <summary>
        ///
        /// </summary>
        public static string[] code_charater = { "---+/aaa/+---", "---+/bbb/+---", "---+/ccc/+---", "---+/ddd/+---", "---+/eee/+---", "---+/fff/+---", "---+/ggg/+---", "---+/hhh/+---", "---+/iii/+---", "---+/jjj/+---", "\\\\u", "\\\\f" };

        #region sha1加密

        /// <summary>
        /// SHA1 加密，返回大写字符串
        /// </summary>
        /// <param name="content">需要加密字符串</param>
        /// <returns>返回40位UTF8 大写</returns>
        public static string SHA1(string content)
        {
            return SHA1(content, Encoding.UTF8);
        }
        /// <summary>
        /// SHA1 加密，返回大写字符串
        /// </summary>
        /// <param name="content">需要加密字符串</param>
        /// <param name="encode">指定加密编码</param>
        /// <returns>返回40位大写字符串</returns>
        public static string SHA1(string content, Encoding encode)
        {
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                byte[] bytes_in = encode.GetBytes(content);
                byte[] bytes_out = sha1.ComputeHash(bytes_in);
                sha1.Dispose();
                string result = BitConverter.ToString(bytes_out);
                result = result.Replace("-", "");
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密出错：" + ex.Message);
            }
        }

        public static string HMACSHA1(string key, string dataToSign)
        {
            byte[] secretBytes = Encoding.UTF8.GetBytes(key);
            HMACSHA1 hmac = new HMACSHA1(secretBytes);
            byte[] dataBytes = Encoding.UTF8.GetBytes(dataToSign);
            byte[] calcHash = hmac.ComputeHash(dataBytes);
            string calcHashString = Convert.ToBase64String(calcHash);
            return calcHashString;
        }

        public static string GetRandomString(int length)
        {
            byte[] b = new byte[4];

            new RNGCryptoServiceProvider().GetBytes(b);

            Random r = new Random(BitConverter.ToInt32(b, 0));

            string s = null, str = "0123456789abcdefghijklmnopqrstuvwxyz";

            for (int i = 0; i < length; i++)
            {
                s += str.Substring(r.Next(0, str.Length - 1), 1);
            }
            return s;
        }

        #endregion

        #region AES加密

        /// <summary>
        /// 默认向量（用于加密/解密）（）
        /// </summary>
        //private const string Iv = "abcdefghijklmnop";

        //string testAES()
        //{
        //    //默认密钥-密钥的长度必须<=32（双方协商）
        //    string PublciKey = "12345678901234567894561235845645";

        //    return AESEncrypt("http://wlx.zhykt.com/api/design/FireExam/ScanCode?admissionTicketNumber=3401211992151515151515", PublciKey);
        //}

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="str">需要加密的字符串</param>
        /// <param name="key">32位密钥</param>
        /// <returns>加密后的字符串</returns>
        public static string AESEncrypt(string str)
        {
            string key = "";
            string Iv = "";

            Byte[] keyArray = Encoding.UTF8.GetBytes(key);
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            var rijndael = new RijndaelManaged();
            rijndael.Key = keyArray;
            rijndael.Mode = CipherMode.ECB;
            rijndael.Padding = PaddingMode.PKCS7;
            rijndael.IV = Encoding.UTF8.GetBytes(Iv);
            ICryptoTransform cTransform = rijndael.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="str">需要解密的字符串</param>
        /// <param name="key">32位密钥</param>
        /// <returns>解密后的字符串</returns>
        public static string AESDecrypt(string str)
        {
            string key = "";
            string Iv = "";

            Byte[] keyArray = Encoding.UTF8.GetBytes(key);
            Byte[] toEncryptArray = Convert.FromBase64String(str);
            var rijndael = new RijndaelManaged();
            rijndael.Key = keyArray;
            rijndael.Mode = CipherMode.ECB;
            rijndael.Padding = PaddingMode.PKCS7;
            rijndael.IV = Encoding.UTF8.GetBytes(Iv);
            ICryptoTransform cTransform = rijndael.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }

        #endregion AES加密

        /// <summary>
        /// 去除html中标签
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string ReplaceHtmlTag(string html)
        {
            if (string.IsNullOrWhiteSpace(html))
            {
                return string.Empty;
            }

            var content = Regex.Replace(html, "<[^>]+>", "");
            return Regex.Replace(content, "\\&[a-zA-Z]{1,10};", "");
        }

        /// <summary>
        /// 2015-9-17 09:21:31
        /// 处理英语音标特殊字符
        /// edit by wl 反斜杠处理
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public static string EncodeSpecialCharacter(string title)
        {
            if (string.IsNullOrWhiteSpace(title))
            {
                return string.Empty;
            }

            title = title.Replace("\\", "\\\\").Replace("\\\\\"", "\\\"");

            for (int i = 0; i < character.Length; i++)
            {
                string chr = character[i];
                string code_chr = code_charater[i];
                title = title.Replace(chr, code_chr);
            }
            return title;
        }

        /// <summary>
        /// 图片类型
        /// </summary>
        public static List<string> ImageType
        {
            get
            {
                return new List<string>
                {
                    "Webp",
                    "BMP",
                    "PCX",
                    "TIFF",
                    "TIF",
                    "GIF",
                    "JPEG",
                    "JPG",
                    "TGA",
                    "EXIF",
                    "FPX",
                    "SVG",
                    "PSD",
                    "CDR",
                    "PCD",
                    "DXF",
                    "UFO",
                    "EPS",
                    "AI",
                    "PNG",
                    "HDRI",
                    "RAW",
                    "WMF",
                    "FLIC",
                    "EMF",
                    "ICO"
                };
            }
        }

        /// <summary>
        /// 是否图片类型
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        public static bool IsImage(string extension)
        {
            return ImageType.Contains(extension, StringComparer.CurrentCultureIgnoreCase);
        }

        /// <summary>
        /// 返回指定的字符串的扩展名。
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetExtension(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return string.Empty;
            }

            try
            {
                var extension = Path.GetExtension(str);

                if (!string.IsNullOrEmpty(extension))
                {
                    return extension.Substring(1, extension.Length - 1);
                }

                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 裁剪图片（OSS）
        /// </summary>
        /// <param name="imageUrl">图片原始OSS地址</param>
        /// <param name="width">宽（默认 100）</param>
        /// <param name="height">高（默认 100）</param>
        /// <returns></returns>
        public static string FormatImageByOSS(string imageUrl, int width = 100, int height = 100)
        {
            if (string.IsNullOrWhiteSpace(imageUrl))
            {
                return string.Empty;
            }

            if (imageUrl.Contains("x-oss-process=image/resize") || !IsImage(GetExtension(imageUrl)))
            {
                return imageUrl;
            }

            return string.Format("{0}?x-oss-process=image/resize,m_fixed,w_{1},h_{2},limit_0", imageUrl, width, height);
        }

        /// <summary>
        /// 获取 省会 坐标
        /// </summary>
        /// <returns></returns>
        public static double[] getProvincialCoordinate(string province)
        {
            double x = 0;
            double y = 0;
            switch (province)
            {
                case "辽宁":
                    x = 123.429092; y = 41.796768;
                    break;
                case "吉林":
                    x = 125.324501; y = 43.886841;
                    break;
                case "黑龙江":
                    x = 126.642464; y = 45.756966;
                    break;
                case "北京":
                    x = 116.405289; y = 39.904987;
                    break;
                case "天津":
                    x = 117.190186; y = 39.125595;
                    break;
                case "内蒙古":
                case "内蒙":
                    x = 111.751990; y = 40.841490;
                    break;
                case "宁夏":
                    x = 106.232480; y = 38.486440;
                    break;
                case "山西":
                    x = 112.549248; y = 37.857014;
                    break;
                case "河北":
                    x = 114.502464; y = 38.045475;
                    break;
                case "山东":
                    x = 117.000923; y = 36.675808;
                    break;
                case "河南":
                    x = 113.665413; y = 34.757977;
                    break;
                case "陕西":
                    x = 108.948021; y = 34.263161;
                    break;
                case "湖北":
                    x = 114.298569; y = 30.584354;
                    break;
                case "江苏":
                    x = 118.76741; y = 32.041546;
                    break;
                case "安徽":
                    x = 117.283043; y = 31.861191;
                    break;
                case "上海":
                    x = 121.472641; y = 31.231707;
                    break;
                case "湖南":
                    x = 112.982277; y = 28.19409;
                    break;
                case "江西":
                    x = 115.892151; y = 28.676493;
                    break;
                case "浙江":
                    x = 120.15358; y = 30.287458;
                    break;
                case "福建":
                    x = 119.306236; y = 26.075302;
                    break;
                case "广东":
                    x = 113.28064; y = 23.125177;
                    break;
                case "台湾":
                    x = 121.5200760; y = 25.0307240;
                    break;
                case "海南":
                    x = 110.199890; y = 20.044220;
                    break;
                case "广西":
                    x = 108.320007; y = 22.82402;
                    break;
                case "重庆":
                    x = 106.504959; y = 29.533155;
                    break;
                case "云南":
                    x = 102.71225; y = 25.040609;
                    break;
                case "贵州":
                    x = 106.713478; y = 26.578342;
                    break;
                case "四川":
                    x = 104.065735; y = 30.659462;
                    break;
                case "甘肃":
                    x = 103.834170; y = 36.061380;
                    break;
                case "青海":
                    x = 101.777820; y = 36.617290;
                    break;
                case "西藏":
                    x = 91.11450; y = 29.644150;
                    break;
                case "新疆":
                    x = 87.616880; y = 43.826630;
                    break;
                case "香港":
                    x = 114.165460; y = 22.275340;
                    break;
                case "澳门":
                    x = 113.549130; y = 22.198750;
                    break;
            }
            double[] data = new double[] { x, y };
            return data;
        }

        #region GET与POST请求方法

        /// <summary>
        /// serviceAddress
        /// get方法调用接口获取json文件内容
        /// </summary>
        /// <param name="serviceAddress"></param>
        /// <returns></returns>
        public static string GetFunction(string serviceAddress, Dictionary<string, string> hearders)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);

            foreach (var item in hearders)
            {
                request.Headers.Add(item.Key.ToString(), item.Value);
            }

            request.Method = "GET";
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }

        /// <summary>
        /// post方法调用接口获取json文件内容
        /// </summary>
        /// <param name="serviceAddress"></param>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public static string PostFunction(string serviceAddress, string strContent)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "POST";
            request.ContentType = "application/json";
            //string strContent = @"{ ""mmmm"": ""89e"",""nnnnnn"": ""0101943"",""kkkkkkk"": ""e8sodijf9""}";
            using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
            {
                dataStream.Write(strContent);
                dataStream.Close();
            }
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8"; //默认编码
                }
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                string retString = reader.ReadToEnd();
                reader.Close();
                return retString;
            }
            catch (Exception ex)
            {
                Console.WriteLine("数据读取错误");
                Console.WriteLine(ex.Message);
            }
            return null;
        }

        #endregion GET与POST请求方法

        #region 统计获取某月每周
        /// <summary>
        /// 统计获取某月每周
        /// 李志航
        /// </summary>
        /// <param name="month">2019-02-01</param>
        /// <returns></returns>
        public static List<WeekJson> getMonthWeek(string month)
        {
            var date = Convert.ToDateTime(month);
            var endDate = date.AddMonths(1).AddDays(-1);
            var allMonthDay = Convert.ToInt32(endDate.ToString("dd"));

            var week = date.DayOfWeek.ToString();
            var weekIndex = getWeekIndex(week);

            var firstWeekInterval = new List<string>();
            var result = new List<WeekJson>();

            firstWeekInterval.Add(date.ToString("yyyy-MM-dd"));
            firstWeekInterval.Add(date.AddDays(6 - weekIndex).ToString("yyyy-MM-dd"));

            var endflg = date.AddDays(6 - weekIndex);

            result.Add(new WeekJson
            {
                weekIndex = 0,
                weekInterval = firstWeekInterval
            });

            var weekFirstDay = endflg.AddDays(1);
            var weekEndDay = weekFirstDay.AddDays(6);

            var twoWeekInterval = new List<string>();

            twoWeekInterval.Add(weekFirstDay.ToString("yyyy-MM-dd"));
            twoWeekInterval.Add(weekEndDay.ToString("yyyy-MM-dd"));

            result.Add(new WeekJson
            {
                weekIndex = 1,
                weekInterval = twoWeekInterval
            });

            var multiple = (allMonthDay - (7 - weekIndex)) / 7;

            for (int i = 2; i <= multiple; i++)
            {
                var weekList = new List<string>();

                weekFirstDay = weekEndDay.AddDays(1);
                weekEndDay = weekFirstDay.AddDays(6);

                weekList.Add(weekFirstDay.ToString("yyyy-MM-dd"));
                weekList.Add(weekEndDay.ToString("yyyy-MM-dd"));

                result.Add(new WeekJson
                {
                    weekIndex = i,
                    weekInterval = weekList
                });
            }

            if ((allMonthDay - weekIndex + 1) % 7 != 0)
            {
                var firstweek = endDate.AddDays(-(getWeekIndex(endDate.DayOfWeek.ToString())));
                var strings = new List<string>();

                strings.Add(firstweek.ToString("yyyy-MM-dd"));
                strings.Add(endDate.ToString("yyyy-MM-dd"));

                result.Add(new WeekJson
                {
                    weekIndex = multiple + 1,
                    weekInterval = strings
                });
            }

            return result;
        }

        static int getWeekIndex(string weekStr)
        {
            switch (weekStr)
            {
                case "Monday":
                    return 0;
                case "Tuesday":
                    return 1;
                case "Wednesday":
                    return 2;
                case "Thursday":
                    return 3;
                case "Friday":
                    return 4;
                case "Saturday":
                    return 5;
                case "Sunday":
                    return 6;
                default:
                    return 0;
            }
        }
        #endregion

        // <summary>
        /// 秒转时分秒
        /// </summary>
        /// <param name="secondTime">秒数</param>
        /// <returns></returns>
        public static string formatSeconds(int secondTime)
        {

            string timeStr = "";

            string min = formatBit(secondTime / 60) + "分";
            string second = formatBit(secondTime % 60) + "秒";

            timeStr = min + second;
            return timeStr;
        }

        /// <summary>
        /// 时间格式
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string formatBit(int time)
        {
            string timeStr = "";

            timeStr = time > 9 ? time.ToString() : "0" + time.ToString();
            return timeStr;
        }
    }

    public class WeekJson
    {
        public int weekIndex { get; set; }

        public List<string> weekInterval { get; set; }
    }
}